"""
认识布局
1、水平、垂直、表格、网格布局（QHBoxLayout，QVBoxLayout，QFormLayout，QGridLayout）
2、组QGroupBox
3、分割器QSplitter
4、空白addStretch/setSpacing
"""

import sys
from typing import Optional
from PySide6.QtGui import Qt
from PySide6.QtWidgets import (QApplication, QCheckBox, QGridLayout, QFormLayout, QGroupBox, QHBoxLayout, QLineEdit, QPlainTextEdit,
                               QPushButton, QSplitter, QVBoxLayout, QWidget)


class LayoutWidget(QWidget):
    def __init__(self, parent: Optional[QWidget] = None) -> None:
        super().__init__(parent=parent)
        self.__init_subwidget()
        self.__init_layout()

    def __init_subwidget(self):
        self.left_push_button = QPushButton("左侧按钮")
        self.right_push_button = QPushButton("右侧按钮")
        self.left_text_editor = QPlainTextEdit("左侧文本编辑器")
        self.right_text_editor = QPlainTextEdit("右侧文本编辑器")
        self.check_box_grid00 = QCheckBox("0，0")
        self.check_box_grid01 = QCheckBox("0，1")
        self.check_box_grid10 = QCheckBox("1，0")
        self.check_box_grid11 = QCheckBox("1，1")
        self.name_line_editor = QLineEdit()
        self.pwd_line_editor = QLineEdit()

    def __init_layout(self):
        # 水平依次添加
        hbox = QHBoxLayout()
        hbox.addWidget(self.left_push_button)
        hbox.addStretch()   # 添加空白
        hbox.addWidget(self.right_push_button)

        # 表格类只有两列，左边为label右边为field，自动为伙伴关系
        form = QFormLayout()
        form.addRow("&用户名：", self.name_line_editor)
        form.addRow("&密码：", self.pwd_line_editor)
        form.setRowWrapPolicy(QFormLayout.WrapAllRows)  # 输入框始终在标签下方

        # 网格+分组
        grp = QGroupBox("checkbox组")
        gbox = QGridLayout()
        gbox.addWidget(self.check_box_grid00, 0, 0)
        gbox.addWidget(self.check_box_grid01, 0, 1)
        gbox.addWidget(self.check_box_grid10, 1, 0)
        gbox.addWidget(self.check_box_grid11, 1, 1)
        grp.setLayout(gbox)
        # 水平Splitter，只能添加widget，如果有复杂的组合，需要自定义新的widget
        hsplitter = QSplitter(Qt.Horizontal)
        hsplitter.addWidget(self.left_text_editor)
        hsplitter.addWidget(self.right_text_editor)
        hsplitter.setStretchFactor(0, 4)
        hsplitter.setStretchFactor(1, 6)    # 4：6比例
        hsplitter.setCollapsible(0, False)  # 左侧不可以完全折叠

        vbox = QVBoxLayout()

        vbox.addLayout(hbox)    # 垂直依次添加
        vbox.setSpacing(50)     # 所有组件间添加50个垂直空白
        vbox.addLayout(form)
        vbox.addWidget(grp)     # groupbox是widget
        vbox.addWidget(hsplitter)   # splitter是widget
        self.setLayout(vbox)


if __name__ == "__main__":
    # 主流程控制，一个程序只能有一个QApplication，sys可以用于命令行导入
    app = QApplication(sys.argv)
    window = LayoutWidget()
    window.show()
    sys.exit(app.exec())               # 控制程序安全退出
